package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
      /*  boolean isPhone = false;
        if(phone.length() == 11){
            isPhone = true;
        }else{
            //2.手机号不符合，返回错误信息
            return  Result.fail("手机号码错误");
        }*/
        if (RegexUtils.isPhoneInvalid(phone)) {
            //可以优化，isPhoneInvalid 是否不是手机号格式，可以改为是否是手机号格式
            return Result.fail("手机号不合格");
        }

        //3.手机号符合，生成验证码
        String code = RandomUtil.randomNumbers(6);

        //4.保存验证码到sessions ！！！！！！！！需要看
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //5.发送验证码
        log.debug("发送验证码成功");
        System.out.println("发送验证码成功" + code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验验证码是否正确
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginForm.getPhone());
        //2.验证码正确校验用户是否存在，存在则登录成功，不存在则创建新用户
        if (cacheCode == null || !cacheCode.equals(loginForm.getCode())) {
            return Result.fail("登陆失败，用户输入验证码不正确");
        }
        //3.寻找用户
        User user = query().eq("phone", loginForm.getPhone()).one();
        //4.用户不存在，创建新用户并保存到数据库
        if (ObjectUtils.isEmpty(user)) {
            User insertUser = new User();
            insertUser.setPhone(loginForm.getPhone());
            insertUser.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomNumbers(10));
            save(insertUser);
        }
/*        //5.将User转为HashMap存在Redis中
        //5.1 随机生成token，作为登陆令牌
        String token = String.valueOf(UUID.randomUUID());
        System.out.println("token = " + token);
        //5.2 把 User 对象转化为HashMap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        //6. 存储
        String tokenKey = LOGIN_USER_KEY + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL,TimeUnit.MINUTES);*/
        String token = UUID.randomUUID().toString();
        String tokenKey = LOGIN_USER_KEY + token;
        UserDTO userDTO = BeanUtil.copyProperties(user,UserDTO.class);
        Map<String,Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue) -> fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL,TimeUnit.SECONDS);
        session.setAttribute("user",user);
        return Result.ok(token);
    }
}
